package com.le.tester.javaThink.fourth.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * createTime：2021/9/15 14:09
 * description：捕获线程run中抛出的异常
 */
class ExceptionThread2 implements Runnable {

    @Override
    public void run() {
        System.out.println("ExceptionThread2 inner================");
        Thread thread = Thread.currentThread();
        System.out.println("run() by " + thread);
        System.out.println("eh=" + thread.getUncaughtExceptionHandler());
        throw new RuntimeException();
    }
}

class MyUncaughtExceptionFactory implements Thread.UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("MyUncaughtExceptionFactory inner");
        System.out.println("caught " + e);
    }
}

//线程开始run之前执行,有异常了又一次回来这里执行
class HandlerThreadFactory implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
        System.out.println("HandlerThreadFactory inner");
        System.out.println(this + " creating new thread");
        Thread thread = new Thread(r);
        System.out.println("created " + thread);
        thread.setUncaughtExceptionHandler(new MyUncaughtExceptionFactory());
        System.out.println("eh=" + thread.getUncaughtExceptionHandler());
        return thread;
    }
}

public class CaptureUncaughtException {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool(new HandlerThreadFactory());
        service.execute(new ExceptionThread2());
    }
}
